{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import, division, print_function, unicode_literals\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import os\n",
    "from face_data_train import CNN\n",
    "import cv2\n",
    "import sys\n",
    "from PIL import Image, ImageDraw, ImageFont\n",
    " \n",
    "if __name__ == '__main__':\n",
    "        \n",
    "    # 加载模型\n",
    "    model = CNN()\n",
    "    model.load_weights('face.h5')  # 读取模型权重参数\n",
    "              \n",
    "    # 框住人脸的矩形边框颜色       \n",
    "    color = (0, 255, 0)\n",
    "    \n",
    "    # 捕获指定摄像头的实时视频流\n",
    "    cap = cv2.VideoCapture(0)\n",
    "    \n",
    "    # 人脸识别分类器本地存储路径\n",
    "    cascade_path =\"/home/yangxf/virtualenvs/tensorflow/lib/python3.8/site-packages/cv2/data/haarcascade_frontalface_alt2.xml\"    \n",
    "    \n",
    "    # 循环检测识别人脸\n",
    "    while True:\n",
    "        ret, frame = cap.read()  # 读取一帧视频\n",
    "        if ret is True:\n",
    "            # 图像灰化，降低计算复杂度\n",
    "            frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n",
    "        else:\n",
    "            continue\n",
    "        # 使用人脸识别分类器，读入分类器\n",
    "        cascade = cv2.CascadeClassifier(cascade_path)                \n",
    " \n",
    "        # 利用分类器识别出哪个区域为人脸\n",
    "        faceRects = cascade.detectMultiScale(frame_gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))        \n",
    "        if len(faceRects) > 0:                 \n",
    "            for faceRect in faceRects: \n",
    "                x, y, w, h = faceRect\n",
    "                # 截取脸部图像提交给模型识别这是谁\n",
    "                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]\n",
    "                face_probe = model.face_predict(image)  # 获得预测值\n",
    "                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, thickness = 2)\n",
    "                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # cv2和PIL中颜色的hex码的储存顺序不同\n",
    "                pilimg = Image.fromarray(frame)\n",
    "                draw = ImageDraw.Draw(pilimg)  # 图片上打印出所有人的预测值\n",
    "                font = ImageFont.truetype(\"simkai.ttf\", 20, encoding=\"utf-8\")  # 参数1：字体文件路径，参数2：字体大小\n",
    "                draw.text((x+25,y-95), '赵:{:.2%}'.format(face_probe[0]), (255, 0, 0), font=font)\n",
    "                draw.text((x+25,y-70), '钱:{:.2%}'.format(face_probe[1]), (255, 0, 0), font=font)\n",
    "                draw.text((x+25,y-45), '孙:{:.2%}'.format(face_probe[2]), (255, 0, 0), font=font)\n",
    "                draw.text((x+25,y-20), '李:{:.2%}'.format(face_probe[3]), (255, 0, 0), font=font)\n",
    "                draw.text((x+25,y-120),'周:{:.2%}'.format(face_probe[4]), (255, 0, 0), font=font)\n",
    "                frame = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)\n",
    "                \n",
    "        cv2.imshow(\"ShowTime\", frame)\n",
    "        \n",
    "        # 等待10毫秒看是否有按键输入\n",
    "        k = cv2.waitKey(10)\n",
    "        # 如果输入q则退出循环\n",
    "        if k & 0xFF == ord('q'):\n",
    "            break\n",
    " \n",
    "    # 释放摄像头并销毁所有窗口\n",
    "    cap.release()\n",
    "    cv2.destroyAllWindows()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
